using System;
using System.Collections.Generic;
using System.Text;
using FBroSharp;
using FBroSharp.Callback;
using FBroSharp.DataType;
using FBroSharp.Lib;
using Newtonsoft.Json;

namespace 虾皮shopee电商数据采集
{
    /// <summary>
    /// Cookie管理器 - 支持导入、导出、设置Cookie
    /// </summary>
    public static class CookieManager
    {
        /// <summary>
        /// 从JSON字符串导入Cookie到浏览器
        /// </summary>
        public static bool ImportCookiesFromJson(IFBroSharpBrowser browser, string url, string cookieJson)
        {
            try
            {
                if (browser == null || !browser.IsValid)
                {
                    Console.WriteLine("[Cookie] 浏览器实例无效");
                    return false;
                }

                // 解析JSON
                var cookies = JsonConvert.DeserializeObject<List<CookieJsonModel>>(cookieJson);
                if (cookies == null || cookies.Count == 0)
                {
                    Console.WriteLine("[Cookie] Cookie列表为空");
                    return false;
                }

                // 获取Cookie管理器
                var cookieManager = (FBroSharpCookieManager)browser.GetRequestContext().GetCookieManager();
                if (cookieManager == null)
                {
                    Console.WriteLine("[Cookie] 无法获取Cookie管理器");
                    return false;
                }

                int successCount = 0;
                int failCount = 0;

                // 遍历设置每个Cookie
                foreach (var cookie in cookies)
                {
                    try
                    {
                        // 创建FBroSharp Cookie数据
                        var fbroCookie = new FBroSharpCookieData
                        {
                            name = cookie.name,
                            value = cookie.value,
                            domain = cookie.domain,
                            path = cookie.path ?? "/",
                            httponly = cookie.httpOnly,
                            secure = cookie.secure ? 1 : 0,  // int类型：0=不安全, 1=安全
                            has_expires = cookie.expirationDate.HasValue,
                            expires_time = cookie.expirationDate.HasValue
                                ? DateTimeOffset.FromUnixTimeSeconds((long)cookie.expirationDate.Value).LocalDateTime
                                : DateTime.MinValue,
                            same_site = 0,
                            priority = 0
                        };

                        // 设置Cookie
                        bool result = cookieManager.SetCookie(url, fbroCookie);
                        if (result)
                        {
                            successCount++;
                            Console.WriteLine($"[Cookie] 成功设置: {cookie.name} = {cookie.value.Substring(0, Math.Min(50, cookie.value.Length))}...");
                        }
                        else
                        {
                            failCount++;
                            Console.WriteLine($"[Cookie] 设置失败: {cookie.name}");
                        }
                    }
                    catch (Exception ex)
                    {
                        failCount++;
                        Console.WriteLine($"[Cookie] 设置Cookie失败 ({cookie.name}): {ex.Message}");
                    }
                }

                Console.WriteLine($"[Cookie] 导入完成：成功 {successCount} 个，失败 {failCount} 个");
                return successCount > 0;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[Cookie] 导入Cookie失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 获取浏览器的所有Cookie（JSON格式）
        /// </summary>
        public static string GetCookiesAsJson(IFBroSharpBrowser browser, string url)
        {
            try
            {
                if (browser == null || !browser.IsValid)
                {
                    return null;
                }

                var cookieManager = (FBroSharpCookieManager)browser.GetRequestContext().GetCookieManager();
                if (cookieManager == null)
                {
                    return null;
                }

                var visitor = new JsonCookieCollectorVisitor();
                cookieManager.VisitUrlCookies(url, true, visitor);

                if (visitor.Help != null && visitor.Help.IsValid)
                {
                    visitor.Help.WaitEvent(10 * 1000);

                    if (visitor.Help.HavStringData())
                    {
                        string jsonResult = visitor.Help.GetStringData();
                        visitor.Help.ClearData();
                        return jsonResult;
                    }
                }

                return null;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[Cookie] 获取Cookie失败: {ex.Message}");
                return null;
            }
        }

        /// <summary>
        /// 清空所有Cookie
        /// </summary>
        public static bool ClearAllCookies(IFBroSharpBrowser browser)
        {
            try
            {
                if (browser == null || !browser.IsValid)
                {
                    return false;
                }

                var cookieManager = (FBroSharpCookieManager)browser.GetRequestContext().GetCookieManager();
                if (cookieManager == null)
                {
                    return false;
                }

                return cookieManager.DeleteCookies("", "");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[Cookie] 清空Cookie失败: {ex.Message}");
                return false;
            }
        }
    }

    /// <summary>
    /// JSON Cookie模型（与浏览器导出格式兼容）
    /// </summary>
    public class CookieJsonModel
    {
        public string domain { get; set; }
        public double? expirationDate { get; set; }
        public bool hostOnly { get; set; }
        public bool httpOnly { get; set; }
        public string name { get; set; }
        public string path { get; set; }
        public string sameSite { get; set; }
        public bool secure { get; set; }
        public bool session { get; set; }
        public string storeId { get; set; }
        public string value { get; set; }
    }

    /// <summary>
    /// JSON格式的Cookie收集访问器
    /// </summary>
    public class JsonCookieCollectorVisitor : FBroSharpCookieVisitor
    {
        public FBroSharpSynHelp Help { get; private set; }
        public int CookieCount { get; private set; }
        private List<object> cookieList;

        public JsonCookieCollectorVisitor()
        {
            Help = new FBroSharpSynHelp();
            cookieList = new List<object>();
            CookieCount = 0;
        }

        public override bool Visit(FBroSharpCookieData cookie, int count, int total, out bool deleteCookie)
        {
            Console.WriteLine($"[Cookie] name: {cookie.name}, value: {cookie.value.Substring(0, Math.Min(20, cookie.value.Length))}..., " +
                             $"domain: {cookie.domain}, 当前: {count + 1}, 合计: {total}");

            // 生成Cookie JSON对象
            var cookieJson = new
            {
                name = cookie.name,
                value = cookie.value,
                domain = cookie.domain,
                path = cookie.path,
                httponly = cookie.httponly,
                secure = cookie.secure,
                has_expires = cookie.has_expires,
                expires_time = cookie.has_expires ? cookie.expires_time.ToString("yyyy-MM-dd HH:mm:ss") : null
            };

            cookieList.Add(cookieJson);
            CookieCount++;

            deleteCookie = false;

            // 如果是最后一个Cookie，序列化为JSON
            if (count + 1 == total)
            {
                string finalJsonArray = JsonConvert.SerializeObject(cookieList, Formatting.Indented);
                Console.WriteLine($"[Cookie] 收集完成，共 {CookieCount} 个");

                Help.SetStringData(finalJsonArray);
                Help.StopEvent();
            }

            return true;
        }
    }
}

